// swiftlint:disable type_name
// swiftlint:disable identifier_name

import Foundation
import MonkeyKing
import Presentr
import RxAlamofire
import RxSwift
import SwiftyJSON
import SKPhotoBrowser
import Kingfisher

let bag = DisposeBag()

// MARK: - 配置支付、分享 Key
struct Configs {

    struct Weibo {
        static let appID = "1772193724"
        static let appKey = "453283216b8c885dad2cdb430c74f62a"
        static let redirectURL = "http://www.limon.top"
    }

    struct WeChat {
        static let appID = "wx4868b35061f87885"
        static let appKey = "64020361b8ec4c99936c0e3999a9f249"
        static let miniAppID = "gh_d43f693ca31f"
    }

    struct QQ {
        static let appID = "1104881792"
    }

    struct Alipay {
        static let appID = "2016012101112529"
    }

}



// MARK: - 使用系统分享
public func showSystemShare(urlStr: String?, title: String?, description: String?, thumbnailImage: UIImage?) {

    let url = URL.init(string: urlStr.or("-"))!
    let info = MonkeyKing.Info(title: title, description: description, thumbnail: thumbnailImage, media: .url(url))
    let sessionMessage = MonkeyKing.Message.weChat(.session(info: info))
    let weChatSessionActivity = AnyActivity(
        type: UIActivityType(rawValue: "com.nixWork.China.WeChat.Session"),
        title: NSLocalizedString("WeChat Session", comment: ""),
        image: UIImage(named: "wechat_session")!,
        message: sessionMessage,
        completionHandler: { success in
            makeToast(message: "分享成功！")
            print("Session success: \(success)")
        }
    )
    let timelineMessage = MonkeyKing.Message.weChat(.timeline(info: info))
    let weChatTimelineActivity = AnyActivity(
        type: UIActivityType(rawValue: "com.nixWork.China.WeChat.Timeline"),
        title: NSLocalizedString("WeChat Timeline", comment: ""),
        image: UIImage(named: "wechat_timeline")!,
        message: timelineMessage,
        completionHandler: { success in
            makeToast(message: "分享成功！")
            print("Timeline success: \(success)")
        }
    )
    let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: [weChatSessionActivity, weChatTimelineActivity])
    windowRootViewController?.present(activityViewController, animated: true, completion: nil)
}

// MARK: - 三方分享，需要配置各应用的key
public func showShareAction(urlStr: String?, title: String?, description: String?, thumbnailImage: UIImage?) {

    let info = MonkeyKing.Info(title: title, description: description, thumbnail: thumbnailImage, media: .url(urlStr.or("").url))
    ///配置分享的按钮,注意需求没有的需要去掉
    let types: [KPShareType] = [.qq, .qzone, .wechat, .wechatTimeline, .wechatFavorite, .weibo]
    let share = KPShareViewController(types: types)
    share.shareInfo = info
    share.view.backgroundColor = .white///调用一次背景颜色，以确保 loadview 被调用
    let size = share.rootLayout.tg_sizeThatFits(CGSize.init(width: Screen.width, height: 0), inSizeClass: .portrait)
    let center = ModalCenterPosition.customOrigin(origin: CGPoint.init(x: 0, y: Screen.height - size.height))
    let present = Presentr.init(presentationType: .custom(width: .full, height: .custom(size: size.height.float), center: center))
    present.dismissOnSwipe = true
    windowRootViewController?.customPresentViewController(present, viewController: share, animated: true, completion: nil)
}

// MARK: - 支付宝、微信支付
public enum PayType {
    case alipay
    case weiChat
}

// MARK: - 注意在比包内分别做不同支付方式的回调
public func payAction(urlStr: String, payType: PayType, completionHandler: @escaping MonkeyKing.PayCompletionHandler) {

    var order: MonkeyKing.Order

    switch payType {
    case .alipay:
        order = MonkeyKing.Order.alipay(urlString: urlStr, scheme: nil)
    default:
        order = MonkeyKing.Order.weChat(urlString: urlStr)
    }

    MonkeyKing.deliver(order) { result in
        print("result: \(result)")
        completionHandler(result)
    }
}

// MARK: - QQ 登录
public func QQLoginAction(_ success: @escaping (_ userInfo: JSON) -> Void) {
    MonkeyKing.oauth(for: .qq, scope: "get_user_info") { (info, _, _) in
        guard
            let info = info,
            let token = info["access_token"] as? String,
            let openID = info["openid"] as? String else {
                return
        }

        let query = "get_user_info"
        let userInfoApi = "https://graph.qq.com/user/\(query)"
        let para = [
            "openid": openID,
            "access_token": token,
            "oauth_consumer_key": Configs.QQ.appID
        ]

        RxAlamofire.requestJSON(.get, userInfoApi, parameters: para)
            .subscribe(onNext: { (_, userInfo) in
                KPLog("userInfo \(String(describing: userInfo))")
                success(JSON.init(userInfo))
            }, onError: { (e) in
                KPLog(e)
            })
            .disposed(by: bag)

    }
}

// MARK: - 微信登录
public func WeChatLoginAction(_ success: @escaping (_ userInfo: JSON) -> Void) {
    MonkeyKing.oauth(for: .weChat) { (oauthInfo, _, _) in
        guard
            let token = oauthInfo?["access_token"] as? String,
            let openID = oauthInfo?["openid"] as? String,
            let refreshToken = oauthInfo?["refresh_token"] as? String,
            let expiresIn = oauthInfo?["expires_in"] as? Int else {
                return
        }
        let userInfoAPI = "https://api.weixin.qq.com/sns/userinfo"
        let parameters = [
            "openid": openID,
            "access_token": token
        ]
        // fetch UserInfo by userInfoAPI

        RxAlamofire.requestJSON(.get, userInfoAPI, parameters: parameters)
            .subscribe(onNext: { (_, userInfo) in
                KPLog("userInfo \(String(describing: json))")
                guard var userInfo = userInfo as? [String: Any] else {
                    return
                }

                userInfo["access_token"] = token
                userInfo["openid"] = openID
                userInfo["refresh_token"] = refreshToken
                userInfo["expires_in"] = expiresIn

                success(JSON.init(userInfo))
            }, onError: { (e) in
                KPLog(e)
            })
            .disposed(by: bag)
    }
}
// MARK: - 查看大图预览图片缓存自定义用 Kingfisher
class KPImageCache:SKImageCacheable {
    func imageForKey(_ key: String) -> UIImage? {
        return ImageCache.default.retrieveImageInDiskCache(forKey: key)
    }

    func setImage(_ image: UIImage, forKey key: String) {
        ImageCache.default.store(image, forKey: key)
    }

    func removeImageForKey(_ key: String) {
        ImageCache.default.removeImage(forKey: key)
    }


}

